#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"
#include "iot_pwm.h"
#include "hi_pwm.h"
#include "hi_time.h"

// 音符频率表（40MHz时钟计算的分频值）
static const uint16_t g_tuneFreqs[] = {
    0,      // 0 休止符
    38223,  // 1 (C4) 261.63Hz
    34052,  // 2 (D4) 293.66Hz
    30338,  // 3 (E4) 329.63Hz
    28635,  // 4 (F4) 349.23Hz
    25511,  // 5 (G4) 392.00Hz
    22728,  // 6 (A4) 440.00Hz
    20249,  // 7 (B4) 493.88Hz
    19111,  // 8 (C5) 523.25Hz 高音1
    17026,  // 9 (D5) 587.33Hz 高音2
    15169   // 10 (E5) 659.26Hz 高音3
};

// 《好运来》副歌简谱（"好运来祝你好运来"核心片段）
static const uint8_t g_scoreNotes[] = {
    8,8,10,8,6,5,5,0,
    8,8,10,8,9,8,0,
    10,10,3,3,10,9,8,0,
    8,6,8,5,5,0,
    8,8,10,8,9,8,0,
    10,10,3,3,10,9,8,0,
    8,6,5,5,5,0
};

// 曲谱时值（4=四分音符，8=八分音符，增强节奏感）
static const uint8_t g_scoreDurations[] = {
    4,4,4,4,4,8,8,4,
    4,4,4,4,4,8,4,
    4,4,4,4,4,4,8,4,
    4,4,4,8,8,4,
    4,4,4,4,4,8,4,
    4,4,4,4,4,4,8,4,
    4,4,8,8,4,4
};

static void beepInit()
{
    hi_gpio_init();
    hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_PWM2_OUT);
    hi_io_set_pull(HI_IO_NAME_GPIO_11, HI_IO_PULL_UP);
    
    hi_pwm_init(HI_PWM_PORT_PWM2);
    hi_pwm_set_clock(PWM_CLK_XTAL);
}

static void beepSingTask(void *arg)
{
    uint32_t tune;
    uint16_t freqDivisor;
    uint32_t tuneInterval;

    beepInit();

    for (size_t i = 0; i < sizeof(g_scoreNotes)/sizeof(g_scoreNotes[0]); i++) {
        tune = g_scoreNotes[i];
        if (tune == 0) {
            hi_udelay(g_scoreDurations[i] * 125 * 1000);
            continue;
        }
        
        freqDivisor = g_tuneFreqs[tune];
        tuneInterval = g_scoreDurations[i] * 125 * 1000;
        
        printf("Playing note %d (divisor=%d) duration=%d\n", 
               tune, freqDivisor, g_scoreDurations[i]);
        
        hi_pwm_start(HI_PWM_PORT_PWM2, freqDivisor/2, freqDivisor);
        hi_udelay(tuneInterval);
        hi_pwm_stop(HI_PWM_PORT_PWM2);
    }
}

static void BeepEntry(void)
{
    osThreadAttr_t attr = {0};
    attr.name = "beepSingTask";
    attr.stack_size = 4096 * 2;
    attr.priority = osPriorityNormal;
    
    if (osThreadNew(beepSingTask, NULL, &attr) == NULL) {
        printf("[BeepEntry] Failed to create beep task!\n");
    }
}

SYS_RUN(BeepEntry);